<template>
  <div class="approval-history">
    <div class="page-header">
      <h2>历史审批记录</h2>
      <p>查看您过往的审批记录</p>
    </div>

    <!-- 搜索条件 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单编号"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="审批结果">
          <el-select
            v-model="searchForm.approvalResult"
            placeholder="请选择审批结果"
            style="width: 150px"
            clearable
          >
            <el-option label="全部" value="" />
            <el-option label="通过" value="approved" />
            <el-option label="拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHistory">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalApprovals }}</div>
              <div class="stat-label">总审批数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number approved">{{ statistics.approvedCount }}</div>
              <div class="stat-label">通过数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number rejected">{{ statistics.rejectedCount }}</div>
              <div class="stat-label">拒绝数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.approvalRate }}%</div>
              <div class="stat-label">通过率</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 审批记录列表 -->
    <div class="history-list">
      <el-table
        :data="historyList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" width="150" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="taskName" label="审批任务" width="150" />
        <el-table-column prop="approvalResult" label="审批结果" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.approvalResult === 'approved' ? 'success' : 'danger'"
              size="small"
            >
              {{ row.approvalResult === 'approved' ? '通过' : '拒绝' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approvalTime" label="审批时间" width="180" />
        <el-table-column prop="rejectReason" label="拒绝原因" min-width="200">
          <template #default="{ row }">
            <span v-if="row.rejectReason">{{ row.rejectReason }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="processInstanceId" label="流程实例ID" width="200" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="viewOrderDetail(row)"
            >
              查看订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <OrderDetail
        v-if="currentOrder"
        :order="currentOrder"
        :readonly="true"
        @close="handleDetailClose"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getApprovalHistory, getApprovalStatistics } from '../../api/flowable.js'
import { getOrderDetail } from '../../api/order.js'
import OrderDetail from './OrderDetail.vue'

// 响应式数据
const loading = ref(false)
const historyList = ref([])
const currentOrder = ref(null)
const detailDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerName: '',
  approvalResult: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 统计信息
const statistics = ref({
  totalApprovals: 0,
  approvedCount: 0,
  rejectedCount: 0,
  approvalRate: 0
})

// 获取当前登录用户
const getCurrentUser = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    return JSON.parse(userInfoStr)
  }
  return null
}

// 加载审批历史
const loadApprovalHistory = async () => {
  try {
    loading.value = true
    const user = getCurrentUser()
    if (!user || !user.username) {
      ElMessage.error('用户信息不完整')
      return
    }

    const params = {
      userName: user.username,
      page: pagination.currentPage,
      size: pagination.pageSize,
      orderNo: searchForm.orderNo,
      customerName: searchForm.customerName,
      approvalResult: searchForm.approvalResult,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }

    const response = await getApprovalHistory(params)
    if (response && response.success) {
      historyList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error('加载审批历史失败')
    }
  } catch (error) {
    console.error('加载审批历史失败:', error)
    ElMessage.error('加载审批历史失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    const user = getCurrentUser()
    if (!user || !user.username) {
      return
    }

    const response = await getApprovalStatistics(user.username)
    if (response && response.success) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 搜索
const searchHistory = () => {
  pagination.currentPage = 1
  loadApprovalHistory()
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = ''
  searchForm.customerName = ''
  searchForm.approvalResult = ''
  searchForm.dateRange = []
  pagination.currentPage = 1
  loadApprovalHistory()
}

// 查看订单详情
const viewOrderDetail = async (row) => {
  try {
    const response = await getOrderDetail(row.orderId)
    if (response && response.success) {
      currentOrder.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentOrder.value = null
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadApprovalHistory()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadApprovalHistory()
}

// 组件挂载时加载数据
onMounted(() => {
  loadApprovalHistory()
  loadStatistics()
})
</script>

<style scoped>
.approval-history {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-number.approved {
  color: #67c23a;
}

.stat-number.rejected {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.history-list {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.text-gray-400 {
  color: #c0c4cc;
}
</style>
